import * as types from '../action-types'
import {getSliders,getLessons} from '../../api/home'
interface setCategoryAction {
  type: string,
  payload: any
}

export type Action = setCategoryAction
export default {
  setCategory(category):setCategoryAction{
    return {type:types.SET_CATEGORY,payload:category}
  },
  getSliders(){
    return function(dispatch,getState){
      getSliders().then(res => {
        let {code,data} = res
        if(code === 0){
          dispatch({type:types.SET_SLIDERS,payload:data})
        }
      })
    }
  },
  getLessons(){
    return function(dispatch,getState){
      let {category,lessons:{offset,limit,loading,hasMore}} = getState().home
      if(!loading && hasMore){
        dispatch({type:types.SET_LOADING})
        getLessons(category,offset,limit).then(res => {
          let {code,data} = res
          if(code === 0){ //派发动作
            dispatch({type:types.SET_LESSONS,payload:data})
          }
        })
      }
    }
  },
  refreshLessons(){
    return function(dispatch,getState){
      let {category,lessons:{offset,limit,loading,hasMore}} = getState().home
      if(!loading ){
        dispatch({type:types.SET_LOADING})
        getLessons(category,0,limit).then(res => {
          let {code,data} = res
          if(code === 0){ //派发动作
            dispatch({type:types.REFRESH_LESSONS,payload:data})
          }
        })
      }
    }
  }
  
 }